<template>
	<section>
		<div class="camera">
			<b-row class="text-center">
				<b-col clos="6">
					<video class="video"></video>
				</b-col>
				<b-col cols="6">
					<canvas class="canvas"></canvas>
				</b-col>
			</b-row>
			<div class="camera-control">
				<button class="camera-btn" @click="cameraOn" v-show="!cameraon">打开摄像头</button>
				<button class="camera-btn" @click="cameraOff" v-if="cameraon">关闭摄像头</button>
				<button class="camera-btn" @click="toCanvas('video')" v-if="cameraon">生成Canvas</button>
			</div>
		</div>
	</section>
</template>
<script type="text/javascript">
import * as getUserMedia from 'getusermedia'

export default {
	data() {
		return {
			videoEl: null,
			canvasEl: null,
			context: null,
			cameraon: false
		}
	},
	components: {

	},
	methods: {
		cameraOn() {
			getUserMedia((err, stream) => {
				if (err) {
					console.log(err)
					this.msg = err.name;
					this.$emit('error', err);
					alert(err)
				} else {
					this.cameraon = true;
					this.stream = stream;
					if (this.videoEl.mozSrcObject !== undefined) { // FF18a
						this.videoEl.mozSrcObject = stream;
					} else if (this.videoEl.srcObject !== undefined) {
						this.videoEl.srcObject = stream;
					} else { // FF16a, 17a
						this.videoEl.src = stream;
					}
				}
			});
		},
		cameraOff() {
			if (this.stream) {
				this.cameraon = false;
				this.msg = this.placement;
				this.context.fillStyle = "#000";
				this.context.fillRect(0, 0, this.ow, this.oh);
				this.stream.getVideoTracks()[0].stop();
				this.canvasGroup = [];
			}
		},
		previewCanvas(el) {
			this.context.fillStyle = "#000";
			this.context.fillRect(0, 0, this.ow, this.oh);
			this.context.drawImage(el.target || el, 0, 0, this.ow, this.oh);
			return this.canvasEl.toDataURL();
		},
		toCanvas() {
			const dataUrl = this.previewCanvas(this.videoEl);
			this.$emit('tocanvas', dataUrl);
			if (this.maxView == 0) {
				return;
			}
			if (this.canvasGroup.length + 1 > this.maxView) {
				this.canvasGroup.pop();
			}
			this.canvasGroup.unshift(this.canvasEl.toDataURL());
		}
	},
	mounted() {
		this.videoEl = this.$el.querySelector('video');
		this.canvasEl = this.$el.querySelector('canvas');
		this.context = this.canvasEl.getContext('2d');

		this.cameraOn();
	},
}

</script>
<style scoped lang="scss">
.camera {
	.video {
		height: 300px; //background-color: #000;
	}
	.canvas {
		height: 300px; //background-color: #000;
	}
}

</style>
